package com.apes.scm.masterdata.product.model;

import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.scm.masterdata.product.model
 * @ClassName: AssetClassification
 * @Author: pyb
 * @Description: 资产分类
 * @CreateTime: 2021-04-22 11:09
 * @Version: 1.0
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = AssetClassification.CONST_TABLE_NAME)
public class AssetClassification extends Model {
    public static final String CONST_TABLE_NAME = "mas_asset_classification";
    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "资产分类",padding = 8)
    private String id;

    @Column(name = "name", nullable = false, length = 120)
    @Comment("资产分类名称")
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parents_id", referencedColumnName = "id")
    @Comment("上级分类编码")
    private AssetClassification parents;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "asset_type", referencedColumnName = "id")
    @Comment("资产类型")
    private Enumeration assetType;

    @OneToMany(mappedBy = "assetClassification", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<AssetClassifyCategory> assetClassifyCategories=new ArrayList<>();

    public List<AssetClassifyCategory> getAssetClassifyCategories() {
        for (AssetClassifyCategory assetClassifyCategory : assetClassifyCategories) {
            assetClassifyCategory.setAssetClassification(this);
        }
        return assetClassifyCategories;
    }


    @Column(name = "levels", nullable = false)
    @Comment("级别")
    private int levels;

    @Column(name = "service_life", nullable = false)
    @Comment("使用年限")
    private int serviceLife;

    @Column(name = "is_last_stage")
    @Comment("末级标记")
    private boolean lastStage;

    @Column(name = "valid", nullable = false, columnDefinition = "number(1,0) default 1")
    @Comment("有效标记")
    private boolean valid;

    @Transient
    private String path;

    public String getPath() {
        String path = null;
        if (parents != null) path = parents.getPath();
        return path != null ? path + "/" + id : id;
    }
}
